<template>

    <!-- 数据添加 -->
    <el-form
      ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules"
      label-width="auto" class="demo-ruleForm" :size="formSize" status-icon >

      <el-form-item label="商品名称" prop="Goods_Name">
        <el-input v-model="ruleForm.Goods_Name" />
      </el-form-item>
      <el-form-item label="商品品牌" prop="BG_Id">
        <el-select v-model="ruleForm.BG_Id" placeholder="请选择商品品牌">
          <el-option v-for="item in BrandInfo" :label="item.Brand_Name" :value="item.Brand_Id" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品分类" prop="newid">
    <el-cascader
      v-model="ruleForm.newid"
      :options="typeoptions"
      :props="props"
      @change="handleChange"
    />
      </el-form-item>
      <el-form-item label="商品价格" prop="Goods_Price">
        <el-input v-model="ruleForm.Goods_Price" />
      </el-form-item>
      <el-form-item label="商品图片" prop="Goods_Img">
        <el-upload
        class="avatar-uploader"
        action="https://localhost:44377/api/FileUpload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
    <img v-if="ruleForm.Goods_Img" :src="ruleForm.Goods_Img" class="avatar" 
      style="width: 150px;height: 120px;"/>
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
      </el-form-item>
    <el-form-item label="商品描述" prop="Goods_Desc">
      <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 200px; overflow-y: hidden;"
        v-model="ruleForm.Goods_Desc"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>
    </el-form-item>

      <el-form-item label="状态" prop="Goods_State">
        <el-radio-group v-model="ruleForm.Goods_State">
          <el-radio :value="true">上架</el-radio>
          <el-radio :value="false">下架</el-radio>
        </el-radio-group>
      </el-form-item>




      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          修改
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </template>
  
  <script lang="ts" setup>
  import { reactive, ref, onMounted, onBeforeUnmount, shallowRef } from 'vue'
  import type { ComponentSize, FormInstance, FormRules,UploadProps } from 'element-plus'
  import axios from 'axios'
  import { ElMessage } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue'
  import '@wangeditor/editor/dist/css/style.css' // 引入 css
  import { useRouter,useRoute } from 'vue-router'
  import { Editor, Toolbar } from '../../../node_modules/@wangeditor/editor-for-vue'

  const router=useRouter()
  const route=useRoute()

onMounted(()=>{
  LoadType()
})

const value = ref([])

const props = {
  expandTrigger: 'hover' as const,
}

const handleChange = (value:any) => {
  console.log(value)
}

const typeoptions = ref([])
const LoadType=()=>{
  
  axios.get("/api/Goods/ShowGoodsType?Pid=0")
  .then(res=>{
    typeoptions.value=res.data.Data

  })
}
  onMounted(()=>{
    LoadBrand()
    LoadData()
  })
  //加载商品信息
  const LoadData=()=>{
    axios.get("/api/Goods/GetGoods?snowid="+route.params.Gid)
    .then(res=>{
        var info=res.data.Data;
        ruleForm.Goods_Id=info.Goods_Id;
        ruleForm.good_SnowId=info.good_SnowId;
        ruleForm.Goods_Name=info.Goods_Name;
        ruleForm.BG_Id=info.BG_Id;
        ruleForm.newid=info.GT_Id.split(',').map((item:number)=>Number(item));
        ruleForm.Goods_Price=info.Goods_Price;
        ruleForm.Goods_Img=info.Goods_Img;
        ruleForm.Goods_Desc=info.Goods_Desc;
        ruleForm.Goods_State=info.Goods_State;
    })
  }
  
  const formSize = ref<ComponentSize>('default')
  const ruleFormRef = ref<FormInstance>()
  //商品信息响应式数据
  const ruleForm = reactive({
    Goods_Id:'',
    good_SnowId:'',
    Goods_Name:'',
    BG_Id:'',
    GT_Id:'',
    Goods_Price:'',
    Goods_Img:'',
    Goods_Desc:'',
    Goods_State:true,
    newid:[]
  })
  
  const locationOptions = ['Home', 'Company', 'School']
  
  //规则验证
  const rules = reactive<FormRules>({
    Goods_Name: [
      { required: true, message: '请输入商品名称', trigger: 'blur' },
      { min: 3, max: 20, message: '商品名称长度介于3-20个字符之间', trigger: 'blur' },
    ],
    BG_Id: [
      {
        required: true,
        message: '商品品牌不能为空',
        trigger: 'change',
      },
    ],
    newid: [
      {
        required: true,
        message: '请选择商品分类',
        trigger: 'change',
      },
    ],
    Goods_Price: [
      {
        required: true,
        message: '请输入价格',
        trigger: 'blur',
      },
    ],
    Goods_Img: [
      {
        required: true,
        message: '请上传图片',
        trigger: 'blur',
      },
    ],
    Goods_Desc: [
      {
        required: true,
        message: '描述信息不能为空',
        trigger: 'blur',
      },
      { min: 12, message: '请输入商品详情,且最少5个字符', trigger: 'blur' },
    ],
    Goods_State: [
      {
        required: true,
        message: '请选择状态',
        trigger: 'change',
      },
    ],
  })
  
  //修改方法
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        ruleForm.GT_Id=ruleForm.newid.toString()
        axios.put("/api/Goods/UpdateGoodsInfo",ruleForm)
        .then(res=>{
          if(res.data.Data>0){
            ElMessage.success("修改成功")
            router.push("/ShowGoods")
          }else if(res.data.Data==-1){
            ElMessage.warning("商品名称已存在")
          }else {
            ElMessage.error("修改失败")
          }
        })
      } else {
        console.log('error submit!', fields)
      }
    })
  }
  
  //重置控件
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
  //表单设置
  const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
  }))
  //创建响应式数据完成商品加载
  const BrandInfo=ref([{
    "Brand_Id": 2,
    "Brand_Name": "华为"
  }])
  //加载品牌信息信息
  const LoadBrand=()=>{
    axios.get("/api/Goods/ShowGoodsBrand")
    .then(res=>{
        if(res.data.Code==200){
            BrandInfo.value=res.data.Data
        }

    })
    .catch(error=>{
        console.log(error)
    })
  }

//上传文件方法
const handleAvatarSuccess=(img:any)=>{
ruleForm.Goods_Img=img
}
//文件格式验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type != 'image/jpeg'&&rawFile.type != 'image/png'&&rawFile.type != 'image/gif') {
    ElMessage.error('图片类型只支持jpg,gif,png格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}
//富文本编辑器
const mode=ref()
  const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p>hello</p>')
  const toolbarConfig = {}
      const editorConfig = { placeholder: '请输入内容...' }

      // 组件销毁时，也及时销毁编辑器
      onBeforeUnmount(() => {
        const editor = editorRef.value
        if (editor == null) return
        editor.destroy()
      })

      const handleCreated = (editor:any) => {
        editorRef.value = editor // 记录 editor 实例，重要！
      }
  </script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
